package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.entity.MallInfo;
import com.qianying.mapper.MallInfoMapper;
import com.qianying.service.ChinaAreaService;
import com.qianying.service.MallInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 商场信息服务实现类
 * 实现商场信息相关的业务逻辑
 */
@Service
public class MallInfoServiceImpl extends ServiceImpl<MallInfoMapper, MallInfo> implements MallInfoService {

    @Autowired
    private MallInfoMapper mallInfoMapper;

    @Autowired
    private ChinaAreaService chinaAreaService;

    /**
     * 分页查询商场信息列表
     */
    @Override
    public CommonResult<IPage<MallInfo>> getPage(Page<MallInfo> page, MallInfo mallInfo) {
        LambdaQueryWrapper<MallInfo> queryWrapper = new LambdaQueryWrapper<>();
        // 商场名称模糊查询
        if (StringUtils.hasText(mallInfo.getMallName())) {
            queryWrapper.like(MallInfo::getMallName, mallInfo.getMallName());
        }
        // 商场编号精确查询
        if (StringUtils.hasText(mallInfo.getMallCode())) {
            queryWrapper.eq(MallInfo::getMallCode, mallInfo.getMallCode());
        }
        // 省市区编码查询
        if (StringUtils.hasText(mallInfo.getProvinceId())) {
            queryWrapper.eq(MallInfo::getProvinceId, mallInfo.getProvinceId());
            if (StringUtils.hasText(mallInfo.getCityId())) {
                queryWrapper.eq(MallInfo::getCityId, mallInfo.getCityId());
                if (StringUtils.hasText(mallInfo.getDistrictId())) {
                    queryWrapper.eq(MallInfo::getDistrictId, mallInfo.getDistrictId());
                }
            }
        }
        // 按ID升序排序
        queryWrapper.orderByAsc(MallInfo::getId);
        // 执行分页查询
        IPage<MallInfo> resultPage = mallInfoMapper.selectPage(page, queryWrapper);
        if (!resultPage.getRecords().isEmpty()) {
            Map<Long, String> areaMap = chinaAreaService.IdToNameMap();
            if (!areaMap.isEmpty()) {
                for (MallInfo record : resultPage.getRecords()) {
                    if (areaMap.containsKey(record.getProvinceId())) {
                        record.setProvinceName(areaMap.get(record.getProvinceId()));
                    }

                    if (areaMap.containsKey(record.getCityId())) {
                        record.setCityName(areaMap.get(record.getCityName()));
                    }

                    if (areaMap.containsKey(record.getDistrictId())) {
                        record.setDistrictName(areaMap.get(record.getDistrictId()));
                    }
                }
            }
        }
        return CommonResult.success(resultPage);
    }

    /**
     * 根据ID查询商场信息详情
     */
    @Override
    public CommonResult<MallInfo> getById(Long id) {
        // 空值校验
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }
        // 查询数据
        MallInfo mallInfo = mallInfoMapper.selectById(id);
        if (mallInfo == null) {
            return CommonResult.failed("未找到ID为" + id + "的商场信息");
        }

        Map<Long, String> areaMap = chinaAreaService.IdToNameMap();
        if (!areaMap.isEmpty()) {
            if (areaMap.containsKey(mallInfo.getProvinceId())) {
                mallInfo.setProvinceName(areaMap.get(mallInfo.getProvinceId()));
            }

            if (areaMap.containsKey(mallInfo.getCityId())) {
                mallInfo.setCityName(areaMap.get(mallInfo.getCityName()));
            }

            if (areaMap.containsKey(mallInfo.getDistrictId())) {
                mallInfo.setDistrictName(areaMap.get(mallInfo.getDistrictId()));
            }
        }
        return CommonResult.success(mallInfo);
    }

    /**
     * 新增商场信息
     */
    @Override
    public CommonResult<?> saveMall(MallInfo mallInfo) {
        // 空值校验
        if (mallInfo == null) {
            return CommonResult.failed("提交的数据不能为空");
        }
        // 主键ID必须为空（自增）
        if (mallInfo.getId() != null) {
            return CommonResult.failed("新增操作ID必须为空");
        }
        // 名称不能为空
        if (!StringUtils.hasText(mallInfo.getMallName())) {
            return CommonResult.failed("商场名称不能为空");
        }

        // 校验商场编号唯一性
        LambdaQueryWrapper<MallInfo> codeWrapper = new LambdaQueryWrapper<>();
        codeWrapper.eq(MallInfo::getMallCode, mallInfo.getMallCode());
        if (mallInfoMapper.selectCount(codeWrapper) > 0) {
            return CommonResult.failed("商场编号已存在");
        }
        mallInfo.setId(null);
        // 执行新增
        int rows = mallInfoMapper.insert(mallInfo);
        return rows > 0 ? CommonResult.success("新增商场信息成功") : CommonResult.failed("新增商场信息失败");
    }

    /**
     * 更新商场信息
     */
    @Override
    public CommonResult<?> updateMall(MallInfo mallInfo) {
        // 空值校验
        if (mallInfo == null) {
            return CommonResult.failed("提交的数据不能为空");
        }
        // ID不能为空
        if (mallInfo.getId() == null) {
            return CommonResult.failed("ID不能为空");
        }
        // 名称不能为空
        if (!StringUtils.hasText(mallInfo.getMallName())) {
            return CommonResult.failed("商场名称不能为空");
        }

        // 校验数据存在性
        MallInfo existing = mallInfoMapper.selectById(mallInfo.getId());
        if (existing == null) {
            return CommonResult.failed("未找到ID为" + mallInfo.getId() + "的商场信息");
        }

        // 校验商场编号唯一性（排除当前ID）
        if (StringUtils.hasText(mallInfo.getMallCode())) {
            LambdaQueryWrapper<MallInfo> codeWrapper = new LambdaQueryWrapper<>();
            codeWrapper.eq(MallInfo::getMallCode, mallInfo.getMallCode())
                    .ne(MallInfo::getId, mallInfo.getId());
            if (mallInfoMapper.selectCount(codeWrapper) > 0) {
                return CommonResult.failed("商场编号已存在");
            }
        }

        // 执行更新
        int rows = mallInfoMapper.updateById(mallInfo);
        return rows > 0 ? CommonResult.success("更新商场信息成功") : CommonResult.failed("更新商场信息失败");
    }

    /**
     * 更新商场启用状态
     */
    @Override
    public CommonResult<?> updateStatus(Long id, Integer status) {
        // 空值校验
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }
        if (status == null || (status != 0 && status != 1)) {
            return CommonResult.failed("状态值无效，必须为0或1");
        }

        // 校验数据存在性
        MallInfo existing = mallInfoMapper.selectById(id);
        if (existing == null) {
            return CommonResult.failed("未找到ID为" + id + "的商场信息");
        }

        // 执行更新
        existing.setStatus(status);
        int rows = mallInfoMapper.updateById(existing);
        return rows > 0 ? CommonResult.success("更新商场状态成功") : CommonResult.failed("更新商场状态失败");
    }

    /**
     * 根据ID删除商场信息
     */
    @Override
    public CommonResult<?> removeById(Long id) {
        // 空值校验
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }
        // 校验数据存在性
        MallInfo existing = mallInfoMapper.selectById(id);
        if (existing == null) {
            return CommonResult.failed("未找到ID为" + id + "的商场信息");
        }
        // 执行删除
        int rows = mallInfoMapper.deleteById(id);
        return rows > 0 ? CommonResult.success("删除商场信息成功") : CommonResult.failed("删除商场信息失败");
    }

    /**
     * 查询所有商场信息（不分页）
     */
    @Override
    public CommonResult<List<MallInfo>> getAll() {
        LambdaQueryWrapper<MallInfo> queryWrapper = new LambdaQueryWrapper<>();
        // 按ID升序排序
        queryWrapper.orderByAsc(MallInfo::getId);
        // 查询所有数据
        List<MallInfo> mallInfoList = mallInfoMapper.selectList(queryWrapper);
        Map<Long, String> areaMap = chinaAreaService.IdToNameMap();
        if (!areaMap.isEmpty()) {
            for (MallInfo record : mallInfoList) {
                if (areaMap.containsKey(record.getProvinceId())) {
                    record.setProvinceName(areaMap.get(record.getProvinceId()));
                }

                if (areaMap.containsKey(record.getCityId())) {
                    record.setCityName(areaMap.get(record.getCityName()));
                }

                if (areaMap.containsKey(record.getDistrictId())) {
                    record.setDistrictName(areaMap.get(record.getDistrictId()));
                }
            }
        }
        return CommonResult.success(mallInfoList);
    }
}